package com.ly.mpayment.rest.system;

import cn.jpush.api.utils.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.CardOrder;
import com.ly.mpayment.persist.entity.User;
import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.callorder.ICardOrderService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.apache.commons.collections.MapUtils.getMap;

@Component
@Path("system/cardorder/")
public class CardOrderRest extends AbsRest {

    Logger logger = Logger.getLogger(DownRechargeFlowRest.class);

    @Autowired
    IUserService userService;

    @Autowired
    ICardOrderService iCardOrderService;

    @Path("findPage")
    @POST
    public String findPage(String data,@Context HttpServletRequest request){
        String result = this.validationParameter(data,request,userService,"start","pageSize","name","operatorname");
        if(result == null){
            Map<String, Object> parameters = MapUtil.getMap();
            JSONObject json = JsonUtils.converToJson(data);
            if(!StringUtils.isEmpty(json.getString("name"))){
                parameters.put(":name", json.getString("name").concat("%"));
            }
            if(!StringUtils.isEmpty(json.getString("operatorname"))){
                parameters.put(":operatorname", json.getString("operatorname"));
            }
            if(!StringUtils.isEmpty(json.getString("cardNum"))){
                parameters.put(":cardNum", json.getString("cardNum"));
            }
            if(!StringUtils.isEmpty(json.getString("upName"))){
                parameters.put(":upName", json.getString("upName"));
            }
            if(!StringUtils.isEmpty(json.getString("upDiscount"))){
                parameters.put(":upDiscount", BigUtil.getBigDecimal(json.getString("upDiscount")));
            }
            if(!StringUtils.isEmpty(json.getString("downName"))){
                parameters.put(":downName", json.getString("downName"));
            }
            if(!StringUtils.isEmpty(json.getString("downDiscount"))){
                parameters.put(":downDiscount", BigUtil.getBigDecimal(json.getString("downDiscount")));
            }
            if(!StringUtils.isEmpty(json.getString("faceValue"))){
                parameters.put(":faceValue", BigUtil.getBigDecimal(json.getString("faceValue")));
            }
            if(!StringUtils.isEmpty(json.getString("status"))){
                parameters.put(":status", json.getInt("status"));
            }
            if(!StringUtils.isEmpty(json.getString("imName"))){
                parameters.put(":imName", json.getString("imName"));
            }
            if(!StringUtils.isEmpty(json.getString("exName"))){
                parameters.put(":exName", json.getString("exName"));
            }
            if(!StringUtils.isEmpty(json.getString("startTime"))){
                parameters.put(":startTime", DateUtils.parseDate(json.getString("startTime")));
            }
            if(!StringUtils.isEmpty(json.getString("endTime"))){
                parameters.put(":endTime", DateUtils.parseDate(json.getString("endTime")));
            }

            return ResultMessage.getSucceed( JsonUtils.excludes(this.iCardOrderService.findPage(parameters, json.getInt("start"), json.getInt("pageSize")),
                    new String[]{"remark","code"}));
        }
        return result;
    }

    @Path("importOrder")
    @POST
    public String importOrder(String data,@Context HttpServletRequest request) {
        String result = this.validationParameterGetRole( request, userService);
        if (result == null && !data.startsWith("{")) {
            String token = request.getHeader("token");
            if (token != null) {
                DecodedJWT jwt;
                try {
                    jwt = JWT.decode(token);
                    if (jwt != null) {
                        JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
                        if (jsonToken != null) {
                            User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
                            if (login != null && UserUtil.checkRole(login)) {
                                JSONArray item = JSONArray.fromObject(data);
                                List<CardOrder> cardOrderList = new ArrayList<CardOrder>();
                                for(int i = 0 ; i < item.size();i++){
                                    CardOrder cardOrder = new CardOrder();
                                    JSONObject ite = item.getJSONObject(i);
                                    cardOrder.setCardNum(ite.getString("cardNum"));
                                    cardOrder.setOperatorname(ite.getString("operatorname"));
                                    cardOrder.setName(ite.getString("name"));
                                    cardOrder.setUpName(ite.getString("upName"));
                                    cardOrder.setUpDiscount(BigUtil.getBigDecimal(ite.getString("upDiscount")));
                                    cardOrder.setDownName(ite.getString("downName"));
                                    cardOrder.setDownDiscount(BigUtil.getBigDecimal(ite.getString("downDiscount")));
                                    cardOrder.setFaceValue(BigUtil.getBigDecimal(ite.getString("faceValue")));
                                    cardOrder.setStatus(ite.getInt("status"));
                                    cardOrder.setImName(login.getUsername());
                                    //cardOrder.setExName(login.getUsername());
                                    //cardOrder.setExTime("");
                                    cardOrder.setPasswd(ite.getString("passwd"));
                                    cardOrder.setCreateTime(new Date());
                                    cardOrder.setExpireTime(DateUtils.parseDate(ite.getString("expireTime")));
                                    cardOrderList.add(cardOrder);
                                }

                                try {
                                    this.iCardOrderService.importOrder(cardOrderList);
                                    return ResultMessage.getSucceed();
                                }catch (Exception e){
                                    e.printStackTrace();
                                    return ResultMessage.getFailt("添加失败,请检查卡号是否重复");
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    @POST
    @Path("exportOrder")
    public String exportOrder(String data,@Context HttpServletRequest request){
        String result = this.validationParameterGetRole(request, userService);
        if(result == null){
            JSONObject json = JsonUtils.converToJson(data);
            Map<String, Object> parameters = MapUtil.getMap();
            String token = request.getHeader("token");
            if (token != null) {
                DecodedJWT jwt;
                try {
                    jwt = JWT.decode(token);
                    if (jwt != null) {
                        JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
                        if (jsonToken != null) {

                            User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
                            //如果是下游客户 只能导出一个月的
                            if(login != null && UserUtil.checkRole(login)){
                                if(com.ly.mpayment.core.util.StringUtils.isBlank(json.getString("startTime"))){
                                    return ResultMessage.getFailt("开始日期必填");
                                }
                                //检查日期不能大于一个月
                                if(com.ly.mpayment.core.util.StringUtils.isBlank(json.getString("endTime"))){
                                    return ResultMessage.getFailt("结束日期必填");
                                }

                                if(!DateUtils.parseYearDay(json.getString("startTime")).equals(DateUtils.parseYearDay(json.getString("endTime")))){
                                    return ResultMessage.getFailt("日期不能跨月");
                                }
                            }

                            if(!StringUtils.isEmpty(json.getString("name"))){
                                parameters.put(":name", json.getString("name").concat("%"));
                            }
                            if(!StringUtils.isEmpty(json.getString("operatorname"))){
                                parameters.put(":operatorname", json.getString("operatorname"));
                            }
                            if(!StringUtils.isEmpty(json.getString("cardNum"))){
                                parameters.put(":cardNum", json.getString("cardNum"));
                            }
                            if(!StringUtils.isEmpty(json.getString("upName"))){
                                parameters.put(":upName", json.getString("upName"));
                            }
                            if(!StringUtils.isEmpty(json.getString("upDiscount"))){
                                parameters.put(":upDiscount", BigUtil.getBigDecimal(json.getString("upDiscount")));
                            }
                            if(!StringUtils.isEmpty(json.getString("downName"))){
                                parameters.put(":downName", json.getString("downName"));
                            }
                            if(!StringUtils.isEmpty(json.getString("downDiscount"))){
                                parameters.put(":downDiscount", BigUtil.getBigDecimal(json.getString("downDiscount")));
                            }
                            if(!StringUtils.isEmpty(json.getString("faceValue"))){
                                parameters.put(":faceValue", BigUtil.getBigDecimal(json.getString("faceValue")));
                            }
                            if(!StringUtils.isEmpty(json.getString("status"))){
                                parameters.put(":status", json.getInt("status"));
                            }
                            if(!StringUtils.isEmpty(json.getString("imName"))){
                                parameters.put(":imName", json.getString("imName"));
                            }
                            if(!StringUtils.isEmpty(json.getString("exName"))){
                                parameters.put(":exName", json.getString("exName"));
                            }
                            if(!StringUtils.isEmpty(json.getString("startTime"))){
                                parameters.put(":startTime", DateUtils.parseDate(json.getString("startTime")));
                            }
                            if(!StringUtils.isEmpty(json.getString("endTime"))){
                                parameters.put(":endTime", DateUtils.parseDate(json.getString("endTime")));
                            }

                            Page<CardOrder> page = this.iCardOrderService.updateExportCallOrder(parameters, json.getInt("start"),
                                    json.getInt("pageSize"),json.containsKey("type") ? json.getString("type") : "");
                            JSONObject obj = JsonUtils.getJSONOBJCT();
                            String exportResult = ExportExcelUtil.exportCallOrder(page);
                            logger.info("exportResult:"+exportResult);
                            if(exportResult != null){
                                obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
                                return ResultMessage.getSucceed(obj.toString());
                            }else{
                                return ResultMessage.getFailt("");
                            }
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    return ResultMessage.getFailt(e.getMessage());
                }
            }
        }
        return result;
    }

    @POST
    @Path("deleteOrder")
    public String deleteOrder(String data,@Context HttpServletRequest request) {
        String result = this.validationParameterGetRole(request, userService);
        if (result == null) {
            JSONObject json = JsonUtils.converToJson(data);

            this.iCardOrderService.deleteById(json.getString("id"));
            return ResultMessage.getSucceed();
        }
        return result;
    }

}
